{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "id": "IUgjtn9xY6G0",
    "colab_type": "code",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 179.0
    },
    "outputId": "7e3ed467-8e97-4c68-bff3-7c56b8f307c0"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-1-042f0e3619f2>:42: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n",
      "Epoch: 1000 cost = 0.130863\n",
      "Epoch: 2000 cost = 0.022833\n",
      "Epoch: 3000 cost = 0.008204\n",
      "Epoch: 4000 cost = 0.003774\n",
      "Epoch: 5000 cost = 0.001942\n",
      "[['i', 'like'], ['i', 'love'], ['i', 'hate']] -> ['dog', 'coffee', 'milk']\n"
     ]
    }
   ],
   "source": [
    "'''\n",
    "  code by Tae Hwan Jung(Jeff Jung) @graykode\n",
    "'''\n",
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "\n",
    "tf.reset_default_graph()\n",
    "\n",
    "sentences = [ \"i like dog\", \"i love coffee\", \"i hate milk\"]\n",
    "\n",
    "word_list = \" \".join(sentences).split()\n",
    "word_list = list(set(word_list))\n",
    "word_dict = {w: i for i, w in enumerate(word_list)}\n",
    "number_dict = {i: w for i, w in enumerate(word_list)}\n",
    "n_class = len(word_dict)\n",
    "\n",
    "# TextRNN Parameter\n",
    "n_step = 2 # number of cells(= number of Step)\n",
    "n_hidden = 5 # number of hidden units in one cell\n",
    "\n",
    "def make_batch(sentences):\n",
    "    input_batch = []\n",
    "    target_batch = []\n",
    "    \n",
    "    for sen in sentences:\n",
    "        word = sen.split()\n",
    "        input = [word_dict[n] for n in word[:-1]]\n",
    "        target = word_dict[word[-1]]\n",
    "\n",
    "        input_batch.append(np.eye(n_class)[input])\n",
    "        target_batch.append(np.eye(n_class)[target])\n",
    "\n",
    "    return input_batch, target_batch\n",
    "\n",
    "# Model\n",
    "X = tf.placeholder(tf.float32, [None, n_step, n_class]) # [batch_size, n_step, n_class]\n",
    "Y = tf.placeholder(tf.float32, [None, n_class])         # [batch_size, n_class]\n",
    "\n",
    "W = tf.Variable(tf.random_normal([n_hidden, n_class]))\n",
    "b = tf.Variable(tf.random_normal([n_class]))\n",
    "\n",
    "cell = tf.nn.rnn_cell.BasicRNNCell(n_hidden)\n",
    "outputs, states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)\n",
    "\n",
    "# outputs : [batch_size, n_step, n_hidden]\n",
    "outputs = tf.transpose(outputs, [1, 0, 2]) # [n_step, batch_size, n_hidden]\n",
    "outputs = outputs[-1] # [batch_size, n_hidden]\n",
    "model = tf.matmul(outputs, W) + b # model : [batch_size, n_class]\n",
    "\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=model, labels=Y))\n",
    "optimizer = tf.train.AdamOptimizer(0.001).minimize(cost)\n",
    "\n",
    "prediction = tf.cast(tf.argmax(model, 1), tf.int32)\n",
    "\n",
    "# Training\n",
    "init = tf.global_variables_initializer()\n",
    "sess = tf.Session()\n",
    "sess.run(init)\n",
    "\n",
    "input_batch, target_batch = make_batch(sentences)\n",
    "\n",
    "for epoch in range(5000):\n",
    "    _, loss = sess.run([optimizer, cost], feed_dict={X: input_batch, Y: target_batch})\n",
    "    if (epoch + 1)%1000 == 0:\n",
    "        print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.6f}'.format(loss))\n",
    "        \n",
    "input = [sen.split()[:2] for sen in sentences]\n",
    "\n",
    "predict =  sess.run([prediction], feed_dict={X: input_batch})\n",
    "print([sen.split()[:2] for sen in sentences], '->', [number_dict[n] for n in predict[0]])"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "TextRNN-Tensor.ipynb",
   "version": "0.3.2",
   "provenance": [],
   "collapsed_sections": []
  },
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  },
  "accelerator": "GPU"
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
